package com.igeek.health.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igeek.health.entity.CheckgroupCheckitem;
import com.igeek.health.entity.Checkitem;
import com.igeek.health.exception.HealthException;
import com.igeek.health.mapper.CheckgroupCheckitemMapper;
import com.igeek.health.mapper.CheckitemMapper;
import com.igeek.health.service.ICheckitemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.health.vo.PageQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fengqq
 * @since 2024-08-26
 *
 * 业务方法上 添加 @Transactional 保证当前业务的事务一致性
 */
@Service
public class CheckitemServiceImpl extends ServiceImpl<CheckitemMapper, Checkitem> implements ICheckitemService {

    @Autowired
    private CheckgroupCheckitemMapper checkgroupCheckitemMapper;

    //根据条件分页查询检查项
    @Transactional(readOnly = true)
    @Override
    public Page<Checkitem> findPage(PageQueryVO vo) {
        if(ObjectUtil.isEmpty(vo)){
            return null;
        }
        Integer currentPage = vo.getCurrentPage();
        Integer pageSize = vo.getPageSize();
        String queryString = vo.getQueryString();

        //封装page对象
        Page<Checkitem> page = new Page<>(currentPage, pageSize);
        //封装条件
        LambdaQueryWrapper<Checkitem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.or().eq(StringUtils.hasLength(queryString),Checkitem::getCode,queryString);
        queryWrapper.or().like(StringUtils.hasLength(queryString),Checkitem::getName,queryString);

        //执行分页查询
        Page<Checkitem> resultPage = this.baseMapper.selectPage(page, queryWrapper);
        return resultPage;
    }

    //根据检查项id删除
    @Transactional
    @Override
    public boolean delete(Integer id) {
        //1.根据检查项id 查询在中间表checkgroup_checkitem中是否有存在数据
        //select count(*) from checkgroup_checkitem where  checkitem_id=28;
        LambdaQueryWrapper<CheckgroupCheckitem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckgroupCheckitem::getCheckitemId,id);
        Long count = checkgroupCheckitemMapper.selectCount(queryWrapper);
        if(count>0){
            //此检查项存在中间表的数据 不能删除
            throw new HealthException("此检查项正在使用中，删除失败");
        }
        //2.count<=0 则不存在中间表的数据 可以删除
        int row = baseMapper.deleteById(id);
        return row>0;
    }

    //查询所有检查项信息
    @Transactional(readOnly = true)
    @Override
    public List<Checkitem> findAll() {
        return baseMapper.selectList(null);
    }
}
